 //
//  TPWechat.swift
//  sonic
//
//  Created by 魔码传媒 on 2017/06/19.
//  Copyright © 2017年 magicode. All rights reserved.
//

import UIKit
import SwiftHTTP
import Locksmith
import HandyJSON
 
protocol DelegateWechatPay:NSObjectProtocol {
    //设置协议方法
    func payDone(status:Bool)
 }

class TPWechat: NSObject,WXApiDelegate
{
    weak static var wechatPayDele:DelegateWechatPay?
    
    func prepareToLogin()
    {
        let accessToken = UserDefaults.standard.object(forKey: kWeiXinAccessToken) as? String
        let openID = UserDefaults.standard.object(forKey: kWeiXinOpenId) as? String
        //如果已经请求过微信授权登录，那么考虑用已经得到的access_token
        if !(accessToken != nil) && (openID != nil)
        {
            let refreshToken:String = UserDefaults.standard.object(forKey: kWeiXinRefreshToken) as! String
            let refreshUrlStr = String.init(format: "%@/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@", kWeixinBaseUrl, kWeiXinAppId, refreshToken)
            
            //发送请求
            do
            {
                let opt = try HTTP.GET(refreshUrlStr, parameters: nil)
                opt.start
                { response in
                    if let err = response.error
                    {
                        print("error: \(err.localizedDescription)")

                        return//also notify app of failure as needed
                    }

                    //print("opt finished: \(response.description)")

                    let data = response.data

                    let dic = try! JSONSerialization.jsonObject(with: data,
                        options: JSONSerialization.ReadingOptions.mutableContainers) as! NSMutableDictionary
                    
                    print("请求reAccess的response = \(data)")
                    
                    let reAccessToken = dic.value(forKey: "access_token")
                    
                    // 如果reAccessToken为空,说明reAccessToken也过期了,反之则没有过期
                    if (reAccessToken != nil)
                    {
                        // 更新access_token、refresh_token、open_id
                        UserDefaults.standard.set(reAccessToken, forKey: kWeiXinAccessToken)
                        UserDefaults.standard.set(dic.value(forKey: "openid"), forKey: kWeiXinOpenId)
                        UserDefaults.standard.set(dic.value(forKey: "refresh_token"), forKey: kWeiXinRefreshToken)
                        UserDefaults.standard.synchronize()
                        // 当存在reAccessToken不为空时直接执行AppDelegate中的wechatLoginByRequestForUserInfo方法
                        //!self.requestForUserInfoBlock ? : self.requestForUserInfoBlock();
                    }
                    else
                    {
                        TPWechat.riseLogin()
                    }
                }
            }
            catch let error
            {
                print("got an error creating the request: \(error)")
//                callback(Result.FAILED)
            }
        }
    }
    
    static func installed() -> Bool
    {
        return WXApi.isWXAppInstalled()
    }
    
//    static func shareToFriend(title:String,url:String)
////    static func shareToFriend(type:ShareType,title:String,url:String)
//    {
//        let message = WXMediaMessage.init()
//        message.title = title
//        
////        message.setThumbImage(self.handleImgWithUriStr(imgUri: url))
//        message.setThumbImage(self.handleImgWithUrlStr(imgUrl: "http://avatar.csdn.net/D/5/9/1_u012716788.jpg"))
//        
////        let webpageObject = WXWebpageObject.init()
////        webpageObject.webpageUrl = CommonShare.GenerateUrl(type, eid: "000")
//        
//        let req = SendMessageToWXReq.init()
//        req.bText = false
//        req.message = message
//        req.scene = Int32(WXSceneSession.rawValue)
//        
//        WXApi.send(req)
//    }
    
    static func shareToFriend(title:String,url:String)
    {
        let message = WXMediaMessage.init()
        message.title = title
        
        let img = self.handleImgWithUriStr(imgUri: url)
        _ = TPWechat.send(image: img, timeline: false)
    }
    
    static func shareToTimeLine(title:String,url:String)
    {
        let message = WXMediaMessage.init()
        message.title = title
        
        let img = self.handleImgWithUriStr(imgUri: url)
        _ = TPWechat.send(image: img, timeline: true)
    }
    
    static func send(image:UIImage, timeline:Bool)->Bool
    {
        let ext=WXImageObject()
        ext.imageData=UIImagePNGRepresentation(image)
        
        let message=WXMediaMessage()
        message.title=nil
        message.description=nil
        message.mediaObject=ext
        message.mediaTagName="MyPic"
        //生成缩略图
        UIGraphicsBeginImageContext(CGSize(width: 100, height: 100))
        image.draw(in: CGRect.init(x: 0, y: 0, width: 100, height: 100))
        let thumbImage=UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        message.thumbData=UIImagePNGRepresentation(thumbImage!)
        
        let req=SendMessageToWXReq()
        req.text=nil
        req.message=message
        req.bText=false
        
        if (timeline)
        {
            req.scene=Int32(WXSceneTimeline.rawValue)
        }
        
        return WXApi.send(req)
    }
    
    static func handleImgWithUrlStr(imgUrl:String) -> UIImage
    {
        let imgData = NSData.init(contentsOf: URL.init(string: imgUrl)!)
        var newImgData = imgData
        
        // 压缩图片data大小
        newImgData = UIImageJPEGRepresentation(UIImage.init(data: newImgData! as Data, scale:0.1)!, 0.1)! as NSData
        let image = UIImage.init(data: newImgData! as Data)
        
        // 压缩图片分辨率(因为data压缩到一定程度后，如果图片分辨率不缩小的话还是不行)
        let newSize = CGSize.init(width: 200, height: 200)
        UIGraphicsBeginImageContext(newSize)
        image?.draw(in: CGRect.init(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImg = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        return newImg!
    }
    
    static func handleImgWithUriStr(imgUri:String) -> UIImage
    {
        let img = UIImage.init(named: imgUri)
        //JEPG格式
//        let imagedata = UIImageJPEGRepresentation(img!,1.0);
//        
////        let imgData = NSData.init(contentsOf: URL.init(string: imgUri)!)
//        var newImgData = imagedata! as NSData
//        
//        // 压缩图片data大小
////        newImgData = UIImageJPEGRepresentation(UIImage.init(data: newImgData! as Data, scale:0.1)!, 0.1)! as NSData
//        
//        newImgData = UIImageJPEGRepresentation(UIImage.init(data: newImgData as Data, scale:0.1)!, 0.1)! as NSData
//        let image = UIImage.init(data: newImgData as Data)
//        
//        // 压缩图片分辨率(因为data压缩到一定程度后，如果图片分辨率不缩小的话还是不行)
//        let newSize = CGSize.init(width: 200, height: 200)
//        UIGraphicsBeginImageContext(newSize)
//        image?.draw(in: CGRect.init(x: 0, y: 0, width: newSize.width, height: newSize.height))
//        let newImg = UIGraphicsGetImageFromCurrentImageContext()
//        UIGraphicsEndImageContext();
//        return newImg!
        
        return img!
    }
    
    //微信登录 第一步
    static func riseLogin()
    {
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo,snsapi_base"
        req.state = kAppDescription
        WXApi.send(req)
    }
    
    static func risePay(para:NSDictionary)
    {
        let request = PayReq.init()
        
        let partnerid = para.value(forKey: "partnerid") as! String
        request.partnerId = partnerid
        
        let prepayid = para.value(forKey: "prepayid") as! String
        request.prepayId = prepayid
        
        let package = para.value(forKey: "package") as! String
        request.package = package
        
        let noncestr = para.value(forKey: "noncestr") as! String
        request.nonceStr = noncestr
        
        let timestamp = para.value(forKey: "timestamp") as! String
        let time = timestamp
        request.timeStamp = UInt32(time)!
        
        let sign = para.value(forKey: "sign") as! String
        request.sign = sign
        
        WXApi.send(request)
    }
    
    //跳转到微信后，得到用户授权结果
    func onResp(_ resp: BaseResp!)
    {
        // 向微信请求授权后,得到响应结果
        if resp.isKind(of:SendAuthResp.self)
        {
            let temp = resp as! SendAuthResp
//            let accessUrlStr = String.init(format: "%@/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", kWeixinBaseUrl, kWeiXinAppId, kWeiXinAppSecret, temp.code)
            let accessUrlStr = String.init(format: "%@/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", kWeixinBaseUrl, SRef.Const(const: .wechat_key), SRef.Const(const: .wechat_secret), temp.code)
            
            //发送请求
            do
            {
                let opt = try HTTP.GET(accessUrlStr, parameters: nil)
                opt.start
                { response in
                    if let err = response.error
                    {
                        print("error: \(err.localizedDescription)")
                        
                        return//also notify app of failure as needed
                    }
                    
                    //print("opt finished: \(response.description)")
                    
                    let data = response.data
                    
                    let dic = try! JSONSerialization.jsonObject(with: data,
                                                                options: JSONSerialization.ReadingOptions.mutableContainers) as! NSMutableDictionary
                    
                    print("请求access的response = \(data)")
                    
                    let accessToken = dic.value(forKey: "access_token") as? String
                    let unionID = dic.value(forKey: "unionid") as? String
                    let refreshToken = dic.value(forKey: "refresh_token") as? String
                    
                    // 本地持久化，以便access_token的使用、刷新或者持续
                    if !(accessToken?.isEmpty)! && !(unionID?.isEmpty)!
                    {
                        UserDefaults.standard.set(accessToken, forKey: kWeiXinAccessToken)
                        UserDefaults.standard.set(unionID, forKey: kWeiXinUnionId)
                        UserDefaults.standard.set(refreshToken, forKey: kWeiXinRefreshToken)
                        UserDefaults.standard.synchronize()// 命令直接同步到文件里，来避免数据的丢失
                    }
                    
                    self.loginByRequestForUserInfo()
                }
            }
            catch let error
            {
                print("获取access_token时出错: \(error)")
                //                callback(Result.FAILED)
            }

        }
        else if resp.isKind(of: PayResp.self)
        {
            switch resp.errCode {
            case 0 :
                print("success paied")
                TPWechat.wechatPayDele?.payDone(status: true)
//                NotificationCenter.defaultCenter().postNotificationName(WXPaySuccessNotification, object: nil)
            default:
                print("retcode = (resp.errCode), retstr = (resp.errStr)")
                TPWechat.wechatPayDele?.payDone(status: false)
            }
        }
        //确保是对我们分享操作的回调
        else if resp.isKind(of: SendMessageToWXResp.self)
        {
            if resp.errCode == WXSuccess.rawValue{//分享成功
                NSLog("分享成功")
            }else{//分享失败
//                NSLog("分享失败，错误码：%d, 错误描述：%@", resp.errCode, resp.errStr)
                NSLog("分享失败")
            }
        }
    }
    
    func onReq(_ req: BaseReq!)
    {
        
    }
    
    // 获取用户个人信息（UnionID机制）
    func loginByRequestForUserInfo()
    {
        let accessToken = UserDefaults.standard.object(forKey:kWeiXinAccessToken) as! String
        let unionID = UserDefaults.standard.object(forKey:kWeiXinUnionId) as! String
        let userUrlStr = String.init(format:"%@/userinfo?access_token=%@&openid=%@", kWeixinBaseUrl, accessToken, unionID)
        
        //发送请求
        do
        {
            let opt = try HTTP.GET(userUrlStr, parameters: nil)
            opt.start
                { response in
                    if let err = response.error
                    {
                        print("error: \(err.localizedDescription)")
                        
                        return//also notify app of failure as needed
                    }
                    
                    //print("opt finished: \(response.description)")
                    
                    let data = response.data
                    
                    let dic = try! JSONSerialization.jsonObject(with: data,
                                                                options: JSONSerialization.ReadingOptions.mutableContainers) as! NSMutableDictionary
                    
                    let wechat = JSONDeserializer<Wechats>.deserializeFrom(dict: dic)
                    
                    do{
//                        try Locksmith.saveData(data: [Key_User_State: Value_User_State_Wechat,
//                                                      Key_User_Id: wechat?.openid as Any,
//                                                      Key_User_Name: wechat?.nickname as Any,
//                                                      Key_User_Head_Path: wechat?.headimgurl as Any
//                                                      ], forUserAccount: Key_User_Account)
                        
                        let refreshToken = UserDefaults.standard.object(forKey: kWeiXinRefreshToken) as! String
                        
                        try Locksmith.updateData(data: [Key_User_State: Value_User_State_Wechat,
                                                        Key_User_Id: wechat?.unionid as Any,
                                                        Key_User_Name: wechat?.nickname as Any,
                                                        Key_User_Token: refreshToken as Any,
                                                        Key_User_Head_Path: wechat?.headimgurl as Any
                            ], forUserAccount: Key_User_Account)
                    }
                    catch let error
                    {
                        print("保存微信用户信息时出错: \(error)")
                        return
                    }
                    
                    print("请求access的response = \(data)")
                    
                    _homeModule?.requestLoadUserData("wechat")
                    
//                    BOOL check = [MGCLoginRegisterViewController genericLoginProcess:[WechatEntity initWithDict:accessDict]];
//                    
//                    if(check)//useless
//                    {
//                        //UIApplication.sharedApplication.delegate.window.rootViewController = [[MGCTabBarController alloc] init];
//                    }
            }
        }
        catch let error
        {
            print("获取access_token时出错: \(error)")
            //                callback(Result.FAILED)
        }

    }
    
}
